package com.seo.service.keyword.impl;

import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.seo.config.KeywrodsConfig;
import com.seo.mapper.keyword.KeywordGMapper;
import com.seo.mapper.keyword.member.KeywordGMemberMapper;
import com.seo.mapper.keyword.memberEidt.KeywordGMemberEMapper;
import com.seo.pojo.KeyWord;
import com.seo.pojo.ReturnBody;
import com.seo.service.keyword.sdk.KeywordGService;
import com.seo.utils.CommonUtil;
import com.seo.utils.CustomUtil;
import com.seo.utils.DateUtil;
import com.seo.utils.HttpClientManagerT;
import com.seo.utils.KeyWordsIndex;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;

@Slf4j
@Service
public class KeywordGServiceImpl implements KeywordGService {

	@Autowired
	private KeywordGMapper keywordGMapper;

	@Autowired
	private KeywordGMemberMapper keywordGMemberMapper;
	
	@Autowired
	private KeywordGMemberEMapper keywordGMemberEMapper;

	@Value("${keyword.5118.baidupc.url}")
	private String baidupcUrl;

	@Value("${keyword.5118.baidumobile.url}")
	private String baidumobileUrl;

	@Value("${keyword.5118.baidupc.api}")
	public String baidupcApikey;

	@Value("${keyword.5118.baidumobile.api}")
	private String baidumobileApikey;

	@Autowired
	private KeywrodsConfig keywrodsConfig;
	
	@Autowired
	private ApplicationContext context;
	
	private ExecutorService threadPoolExecutor = Executors.newFixedThreadPool(2);

	private ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(2);
	
	private List<Map<String, Object>> apiErrorList = new ArrayList<>();

	/**
	 * 关键词列表
	 */
	public List<Map<String, Object>> getKeyWordsList(Map<String, Object> pam) {
		log.info("进入关键词列表service：");
		List<Map<String, Object>> keyWordsList = keywordGMapper.getKeyWordsList(pam);
		log.info("关键词列表查询数据：" + keyWordsList);
		return keyWordsList;
	}

	@Override
	public List<Map<String, Object>> getKeyWordsReviewList(Map<String, Object> pam) {
		log.info("进入关键词审核列表service：");
		List<Map<String, Object>> keyWordsReviewList = keywordGMapper.getKeyWordsReviewList(pam);
		log.info("关键词审核列表查询数据：" + keyWordsReviewList);

		return keyWordsReviewList;
	}

	/**
	 * 删除
	 */
	public void deleteArr(Map<String, Object> pam) {
		keywordGMapper.deleteArr(pam);
	}
	
	public ReturnBody deleteArrByDay(Map<String, Object> pam) {
		ReturnBody rb = ReturnBody.init();
		if(!pam.containsKey("ids")) {
			log.error("参数为空");
			return rb.rollback("参数为空");
		}
		
		List<Map<String, Object>> list = keywordGMemberEMapper.getKeyWordsEList(pam);
		if(list == null || list.isEmpty()) {
			log.error("关键词不存在");
			return rb.rollback("关键词不存在");
		}
		for(Map<String, Object> obj : list) {
			Integer useDay = CommonUtil.getIntegerByObject(obj.get("useDay"));
			Integer reachDays = CommonUtil.getIntegerByObject(obj.get("reachDays"));
			Integer consumeDays = CommonUtil.getIntegerByObject(obj.get("consumeDays"));
			if(reachDays > 0  && consumeDays < 30) {
				return rb.rollback("已达标关键词，消费30天后可删除");
			}
			if(reachDays == 0  && useDay < 15) {
				return rb.rollback("未达标关键词，使用15天后可删除");
			}
			Long id = (Long)obj.get("id");
			int num = keywordGMapper.deleteById(id);
			if(num == 0) {
				log.error("关键词删除失败");
				return rb.rollback("关键词删除失败");
			}
		}
		return rb.success();
		
	}

	/**
	 * 批量修改厂商
	 */
	public ReturnBody updateVender(Map<String, Object> pam) {
		ReturnBody rb = ReturnBody.init();
		try {
			int num = keywordGMapper.updateVender(pam);
			keywordGMemberMapper.updateProxyVender(pam);
			if (num == 0) {
				return rb.rollback();
			}
			return rb.success();
		} catch (Exception e) {
			log.error("异常-{}", e);
			return rb.rollback();
		} finally {
			rb.result();
		}

	}

	/**
	 * 获取厂商
	 */
	public List<Map<String, Object>> getVenderList() {
		return keywordGMapper.getVenderList();
	}

	/**
	 * 修改关键词
	 * 
	 * @param pam
	 * @return
	 */
	public ReturnBody updatekeyWordState(Map<String, Object> pam, List<KeyWord> keyWordSucessList) {
		ReturnBody rb = ReturnBody.init();
		ReturnBody rbImport = ReturnBody.init();
		try {
			JSONArray idArray = JSONArray.fromObject(pam.get("dat"));
			List<Map<String, Object>> jsonList = (List<Map<String, Object>>) JSONArray.toList(idArray, Map.class);
			String state = (String) pam.get("state");
			if (StringUtils.isNotEmpty(state)) {
				for (int i = 0; i < jsonList.size(); i++) {
					Map<String, Object> keyWordMap = jsonList.get(i);
					String id = keyWordMap.get("id").toString();
					pam.put("ids", id);
					int num = keywordGMapper.updatekeyWordReview(pam);
					if (num == 0) {
						return rb.rollback();
					}
					keywordGMemberMapper.updateProxyKeyWordReview(pam);

				}
				rb.put("keyWordSucessList", keyWordSucessList);
				String importime = DateUtil.yMdToYmdmds(DateUtil.getDay());
				rbImport = importDataToDataBase(rb, importime);
				if (!rbImport.isSuccess()) {
					rb.rollback();
					return rb.rollback();
				}
			}
			return rb.success();
		} catch (Exception e) {
			log.error("异常-{}", e);
			return rb.rollback();
		} finally {
			rb.result();
		}
	}

	/**
	 * 关键词审核
	 */

	public void keyWordReview(Map<String, Object> pam) {
		ReturnBody rb = ReturnBody.init();
		try {
			JSONArray idArray = JSONArray.fromObject(pam.get("dat"));
			List<Map<String, Object>> jsonList = (List<Map<String, Object>>) JSONArray.toList(idArray, Map.class);
			String state = (String) pam.get("state");
			if (StringUtils.isNotEmpty(state)) {
				List<KeyWord> keyWordSucessList = new ArrayList<KeyWord>();
				for (int i = 0; i < jsonList.size(); i++) {
					Map<String, Object> keyWordMap = jsonList.get(i);
					String id = keyWordMap.get("id").toString();
					String keyword = keyWordMap.get("keyWordName").toString();
					String engineCode = keyWordMap.get("engine_code").toString();
					String domain = keyWordMap.get("domain").toString();
					pam.put("ids", id);
					if ("01".equals(state)) {
						rb.run(KeyWordsIndex.getKeyWordsRanking(keyword, domain, engineCode));
						if (rb.isSuccess()) {
							String ranking = (String) rb.get("ranking");
							log.info("最新排名：" + ranking);
							KeyWord keyWord = new KeyWord();
							;
							if (StringUtils.isNotEmpty(keyword)) {
								keyWord.setName(keyword); // 关键词
							} else {
								return;
							}
							if (StringUtils.isNotEmpty(domain)) {
								keyWord.setDomain(domain); // 域名
							} else {
								return;
							}
							if (StringUtils.isNotEmpty(engineCode)) {
								keyWord.setEngineCode(engineCode);// 搜索引擎
							} else {
								return;
							}
							if (StringUtils.isNotEmpty(ranking)) {
								keyWord.setNewRanking(ranking); // 新排
							} else {
								return;
							}
							keyWordSucessList.add(keyWord);
						} else {
							rb.rollback();
							return;
						}
					}
				}
				rb = ((KeywordGServiceImpl) AopContext.currentProxy()).updatekeyWordState(pam, keyWordSucessList);
			}
		} catch (Exception e) {
			log.error("异常-{}", e);
			rb.rollback();
		} finally {
			rb.result();
		}
	}

	/**
	 * 导入
	 */
	@Transactional
	public ReturnBody importKeyWord(String fileName, MultipartFile file, String importTime) throws Exception {
		ReturnBody rb = ReturnBody.init();
		try {
			long a = System.currentTimeMillis();
			log.info("校验excel格式、版本");
			if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
				log.error("上传文件格式不正确");
			}
			boolean isExcel2003 = true;
			if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
				isExcel2003 = false;
			}
			InputStream is = file.getInputStream();
			Workbook wb = null;
			if (isExcel2003) {
				wb = new HSSFWorkbook(is);
			} else {
				wb = new XSSFWorkbook(is);
			}
			Sheet sheet = wb.getSheetAt(0);
			/********************* 获取excel的头部 ****************************************/
			log.info("校验excel头部");
			String title = checkTitle(sheet); // 返回结果 00 代表没有识别到规定的excel 01
												// 厂商导入excel 02 搜索引擎排名excel
			if ("01".equals(title)) { // 01 厂商导入
				rb = venderImport(sheet);
			} else if ("02".equals(title)) { // 02 搜索引擎排名导入
				rb = engineImport(sheet);
			}
			log.info("\r<br>读excl耗时 : " + (System.currentTimeMillis() - a) / 1000f + " 秒 ");
			if (!rb.isSuccess()) {
				rb.put("msg", "导入失败");
				return rb;
			}
			rb = importDataToDataBase(rb, importTime);
			return rb;
		} catch (Exception e) {
			log.error("异常-{}", e);
			return rb.rollback();
		} finally {
			rb.result();
		}
	}

	/**
	 * 导入插入数据
	 * 
	 */
	public ReturnBody importDataToDataBase(ReturnBody rb, String importTime) {
		List<KeyWord> keyWordError = new ArrayList<>();
		List<KeyWord> keyWordSucessList = rb.getCollection("keyWordSucessList", KeyWord.class);
		Map<String, Object> pam = new HashMap<>();
		StringBuffer errorBu = new StringBuffer();
		long b = System.currentTimeMillis();
		int errNum = 0;
		// 开始把数据插入到数据库中
		for (int i = 0; i < keyWordSucessList.size(); i++) {
			KeyWord keyWord = keyWordSucessList.get(i);
			try {
				if (errorBu.length() > 0) {
					errorBu.delete(0, errorBu.length() - 1);
				}
				
				String keyWordName = keyWord.getName(); // 关键词
				String domain = keyWord.getDomain(); // 域名
				String engineCode = keyWord.getEngineCode(); // 引擎
				pam.clear();
				pam.put("keyWordName", keyWordName);
				pam.put("domain", domain);
				pam.put("engineCode", engineCode);
				// 根据关键词，域名和引擎查询 主表详情数据
				Map<String, Object> keyWordInfo = keywordGMapper.getInfoByDomainAndKeyword(pam);
				/*
				 * 第一次判断：主表 根据域名和关键词查询数据 如果 有值 就更新数据 否则 跳过 第二次判断： 在更新数据之前 根据前台页面传过来的time 时间
				 * 和主表中的 run_time时间做比较 主表 如果 time>=run_time 则更新数据 否则 跳过
				 * 
				 * 明细表落地数据 的前提是 导入的数据 主表中必须存在 否则 不进行落地 首先 根据关键词主表id和run_time作为条件
				 * （run_time等于前台页面穿的time） 查询明细表 是否有值 如果有值 进行修改 没有值 进行添加 在修改之前 根据前台传过来的time 和
				 * 明细表中的 run_time时间进行比较
				 * 
				 * 代理表数据更新的前提是 导入的数据主表中必须存在 否则 不进行更新 根据主表的id 查询代理表 是否有这条数据 有就更新 代理表 没有 跳过
				 * 
				 */
				if (keyWordInfo != null) { // 根据域名和关键词查询数据 如果 有值 就更新数据 否则 跳过
					Long keyWordId = (Long) keyWordInfo.get("id");
					String runTime = (String) keyWordInfo.get("run_time");
					int initRanking = (int) keyWordInfo.get("init_ranking");
					int targetRanking = (int) keyWordInfo.get("target_ranking"); // 目标排名
					int newRanking = (int) keyWordInfo.get("new_ranking");// 最新排名
					int reachDays = 0;
					Integer importNewRanking = Integer.parseInt(keyWord.getNewRanking()); // 导入的最新排名
					Map<String, Object> dataSorting = DataSorting(keyWord); // 数据整理
					if (targetRanking >= importNewRanking && targetRanking < newRanking) {
						reachDays = 1;
					} else if (targetRanking >= newRanking && targetRanking < importNewRanking) {
						reachDays = -1;
					}

					if (targetRanking >= importNewRanking) { // 如果目标排名大于等于
																// 导入的最新排名
																// 那么就算达标
						dataSorting.put("isTarget", "01"); // 达标
						keyWordInfo.put("is_target", "01"); // 达标
					} else {
						dataSorting.put("isTarget", "00"); // 未达标
						keyWordInfo.put("is_target", "00"); // 未达标
					}
					dataSorting.put("keyWordId", keyWordId);

					if (initRanking == -1) { // 只有 初排 为-1的时候 才更新初排 否则就不更新
						dataSorting.put("initRanking", keyWord.getNewRanking());// 初排
					}
					Map<String, Object> proxyKeyWordInfo = null;
					if (StringUtils.isEmpty(runTime)) {
						dataSorting.put("importTime", importTime);
						// 更新主表数据
						int primaryNum = keywordGMapper.updateKeyword(dataSorting);
						if (primaryNum > 0) {
							// 更新主表数据 更新主表完毕 在进行 代理表的更新
							// proxyKeyWordInfo是否有这条数据 有就更新 代理表 没有 跳过
							// 根据主表的id 查询代理表
							proxyKeyWordInfo = keywordGMapper.getProxyByKeyWordId(keyWordId);
							if (proxyKeyWordInfo != null && proxyKeyWordInfo.size() > 0) { // 更新代理表数据
								keywordGMapper.updateProxyKeyword(dataSorting);
							}
						}
						// 此处赋值 是为啦下面进行修改昨日排名准备的
						runTime = importTime;
					} else {
						// importTime 时间 和主表中的 run_time时间做比较 如果t为true 则说明
						// time>=run_time 更新数据 否则跳过
						boolean t = DateUtil.compareDate(importTime, runTime);
						if (t) { // t为true 则说明 importTime>=run_time 更新数据 否则跳过
							dataSorting.put("importTime", importTime);
							// 更新主表数据
							int primaryNum = keywordGMapper.updateKeyword(dataSorting);
							if (primaryNum > 0) {
								// 更新主表数据 更新主表完毕 在进行 代理表的更新
								// proxyKeyWordInfo是否有这条数据 有就更新 代理表 没有 跳过
								// 根据主表的id 查询代理表
								proxyKeyWordInfo = keywordGMapper.getProxyByKeyWordId(keyWordId);
								if (proxyKeyWordInfo != null && proxyKeyWordInfo.size() > 0) { // 更新代理表数据
									keywordGMapper.updateProxyKeyword(dataSorting);
								}
							}
							// 此处赋值 是为啦下面进行修改昨日排名准备的
							runTime = importTime;
						}

					}
					String target = (String) keyWordInfo.get("is_target");
					// 根据主表中的id 以及 前台传入的runtime时间
					// 在seo_keywords_user_detail进行查询详情
					Map<String, Object> pamDetail = new HashMap<>();
					pamDetail.put("keyWordId", keyWordId);
					pamDetail.put("importTime", importTime);
					Map<String, Object> keywordsUserDetailInfo = keywordGMapper.getInfoByKeyWordIdAndRuntime(pamDetail);
					// 如果 有值 就更新数据 否则 添加数据
					if (keywordsUserDetailInfo != null) {
						// 明细表中的达标字段 如果is_target=01 说明已经达标 那么说明今天的达标天数字段已经更新过一次
						dataSorting.put("importTime", importTime);

						if (reachDays != 0) {
							// 如果关键词明细表中添加数据 并且 这条excl数据 也达标啦 那么就在主表中 更改达标天数
							// +1
							Map<String, Object> reachMap = new HashMap<>();
							reachMap.put("keyWordId", keyWordId);
							reachMap.put("reachDays", reachDays);
							keywordGMapper.updateKeyword(reachMap);
							keywordGMapper.updateProxyKeyword(reachMap);

						}
						dataSorting.put("reachDays", reachDays < 0 ? 0 : reachDays);
						dataSorting.put("price", keyWordInfo.get("price"));
						if (proxyKeyWordInfo != null && proxyKeyWordInfo.size() > 0) {
							dataSorting.put("price_1", keyWordInfo.get("price")); // 代理表价格
						}
						keywordGMapper.updateKeywordDetail(dataSorting);
					} else {
						// keyWordInfo 主表查询结果 proxyKeyWordInfo代理表查询的结果
						// importTime前台传的时间 keyWord excel文档的数据
						Map<String, Object> detailMap = keywordsUserDetailSorting(keyWordInfo, proxyKeyWordInfo,
								importTime, keyWord);
						keywordGMapper.addKeywordsUserDetail(detailMap);
						// 添加的时候 明细表中不可能有达标数据 都是主表中的数据 主表已经达标 那么就要在主表中的达标天数 +1
						// 否则不更新
						if ("01".equals(target)) {
							// 如果关键词明细表中添加数据 并且 这条excl数据 也达标啦 那么就在主表中 更改达标天数 +1
							Map<String, Object> reachMap = new HashMap<>();
							reachMap.put("keyWordId", keyWordId);
							reachMap.put("reachDays", 1);
							keywordGMapper.updateKeyword(reachMap);
							keywordGMapper.updateProxyKeyword(reachMap);
						}
					}
					Map<String, Object> afterDetail = new HashMap<>();
					// 修改昨日排名
					String afterDate = DateUtil.getAfterDayDate(runTime, -1, 1);
					afterDetail.put("keyWordId", keyWordId);
					afterDetail.put("importTime", afterDate);
					// 查询出来昨天的 明细数据 然后进行判断 最新排名 如果最新排名为 -1 则不做任何修改 如果不是-1
					// 把主表的昨日排名 修改为 明细中的最新排名
					Map<String, Object> afterKeywordsUserDetailInfo = keywordGMapper
							.getInfoByKeyWordIdAndRuntime(afterDetail);
					if (afterKeywordsUserDetailInfo != null) {
						Integer ydayRanking = (Integer) afterKeywordsUserDetailInfo.get("new_ranking");
						if (!"-1".equals(ydayRanking)) {
							Map<String, Object> reachMap = new HashMap<>();
							reachMap.put("keyWordId", keyWordId);
							reachMap.put("ydayRanking", ydayRanking);
							keywordGMapper.updateKeyword(reachMap);
							keywordGMapper.updateProxyKeyword(reachMap);
						}
					}
				} else {
					errNum += 1;
					keyWordError.add(keyWord);
				}

			} catch (Exception e) {
				log.error("第" + (i + 2) + "行导入失败[{}]", e);
				keyWordError.add(keyWord);
			}
		}
		rb.put("keyWordError", keyWordError);
		rb.put("errNum", errNum);
		log.info("\r<br>插入数据库耗时 : " + (System.currentTimeMillis() - b) / 1000f + " 秒 ");
		return rb.success();
	}

	/**
	 * 修改数据整理
	 * 
	 * @return
	 */
	public Map<String, Object> DataSorting(KeyWord keyWord) {
		Map<String, Object> pam = new HashMap<>();
		pam.put("keyWordName", keyWord.getName());// 关键词
		pam.put("domain", keyWord.getDomain());// 域名
		pam.put("keyWordIndex", keyWord.getKeywordIndex());// 关键词指数
		pam.put("engineCode", keyWord.getEngineCode());// 关键词引擎
		pam.put("newRanking", keyWord.getNewRanking());// 新排
		pam.put("isInclude", keyWord.getIsInclude());// 是否收录
		return pam;
	}

	/**
	 * 整理明细表数据
	 * 
	 * @param keyWord
	 * @return
	 */
	public Map<String, Object> keywordsUserDetailSorting(Map<String, Object> primaryMap, Map<String, Object> proxyMap,
			String importTime, KeyWord keyWord) {
		Map<String, Object> pam = new HashMap<>();
		pam.put("run_time", importTime); // 执行时间
		pam.put("keywords_id", primaryMap.get("id")); // 主表id
		pam.put("name", keyWord.getName()); // 关键词
		pam.put("user_id", primaryMap.get("user_id")); // 用户id
		pam.put("real_user_id", primaryMap.get("real_user_id")); // 用户id
		pam.put("engine_code", keyWord.getEngineCode()); // 引擎
		pam.put("price", primaryMap.get("price")); // 主表价格
		pam.put("domain", keyWord.getDomain()); // 域名
		pam.put("keyword_index", keyWord.getKeywordIndex()); // 指标
		pam.put("target_ranking", primaryMap.get("target_ranking")); // 目标排名
		pam.put("new_ranking", keyWord.getNewRanking()); // 最新排名
		pam.put("is_target", primaryMap.get("is_target")); // 是否达标
		String isTarget = (String) primaryMap.get("is_target");
		if ("01".equals(isTarget)) {
			pam.put("reach_days", 1);
		} else {
			pam.put("reach_days", 0);
		}
		pam.put("is_include", primaryMap.get("is_include")); // 是否收录
		pam.put("remark", primaryMap.get("remark")); // 备注
		pam.put("create_time", DateUtil.getTime()); // 创建时间
		pam.put("update_time", DateUtil.getTime()); // 修改时间
		pam.put("create_id", primaryMap.get("create_id")); // 创建人
		pam.put("update_id", primaryMap.get("update_id")); // 修改人
		if (proxyMap != null && proxyMap.size() > 0) {
			pam.put("proxy_user_id", proxyMap.get("proxy_user_id")); // 代理id
			pam.put("price_1", proxyMap.get("price")); // 代理表价格
		}
		return pam;
	}

	/**
	 * 判断导入的excel是哪种类型的excel
	 * 
	 * @param sheet
	 * @return String res 返回结果为00 代表没有识别到规定的excel 01 厂商导入excel 02 搜索引擎排名excel
	 */
	public String checkTitle(Sheet sheet) {
		// 获取excel第一行的 title数据
		Row title = sheet.getRow(0);
		log.info("获取title：" + title);
		String oneName = title.getCell(0).getStringCellValue(); // 第一列是关键字
		String twoName = title.getCell(1).getStringCellValue(); // 第二列是关键字
		String threeName = title.getCell(2).getStringCellValue(); // 第三列是关键字
		String foutName = title.getCell(3).getStringCellValue(); // 第四列是关键字
		String fiveName = title.getCell(4).getStringCellValue(); // 第五列是关键字
		String sixName = title.getCell(5).getStringCellValue(); // 第六列是关键字
		String sevenName = title.getCell(6).getStringCellValue(); // 第七列是关键字
		String res = "00"; // 返回结果为00 代表没有识别到规定的excel 01 厂商导入excel 02
							// 搜索引擎排名excel
		if ("关键词".equals(oneName) && "域名".equals(twoName) && "指数".equals(threeName) && "类型".equals(foutName)
				&& "初排".equals(fiveName) && "新排".equals(sixName) && "创建日期".equals(sevenName)) {
			res = "01";
		} else if ("序号".equals(oneName) && "关键词".equals(twoName) && "网址".equals(threeName) && "搜索引擎".equals(foutName)
				&& "收录".equals(fiveName) && "排名".equals(sixName) && "名称".equals(sevenName)) {
			res = "02";
		} else {
			res = "00";
		}
		return res;

	}

	/**
	 * 过滤域名 把http和https去掉
	 * 
	 * @param urlName
	 * @return
	 */
	public String filterDoim(String urlName) {
		URI url;
		String domain = null;
		try {
			url = new URI(urlName);
			if ("http".equals(url.getScheme())) {
				domain = urlName.substring(7, urlName.length());
			} else if ("https".equals(url.getScheme())) {
				domain = urlName.substring(8, urlName.length());
			} else {
				domain = urlName;
			}
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		return domain;
	}

	/**
	 * 厂商导入
	 * 
	 * @param sheet sheet
	 * @return ReturnBody rb
	 */
	public ReturnBody venderImport(Sheet sheet) {
		ReturnBody rb = ReturnBody.init();
		List<KeyWord> keyWordSucessList = new ArrayList<KeyWord>();
		List<StringBuffer> keyWordErrorList = new ArrayList<StringBuffer>();
		List<Map<String, Object>> engineList = keywordGMapper.getEngineList();
		KeyWord keyWord;
		int importNum = 0; // 记录一共导入多少条数据
		for (int r = 1; r <= sheet.getLastRowNum(); r++) {
			StringBuffer resBu = new StringBuffer();
			if (resBu.length() > 0) {
				resBu.delete(0, resBu.length() - 1);
			}
			try {
				Row row = sheet.getRow(r);
				if (row == null) {
					continue;
				}
				keyWord = new KeyWord();
				String name = null;
				String domain = null;
				String domainStr = null;
				String keyWordIndex = null;
				String engine = null;
				String initRanking = null;
				String newRanking = null;
				// 关键词
				if (row.getCell(0) != null) {
					name = row.getCell(0).getStringCellValue();
					if (name == null || name.isEmpty()) {
						log.error("导入失败(第" + (r + 1) + "行,关键字未填写)");
						resBu.append("导入失败(第" + (r + 1) + "行,关键字未填写)");
					}
				} else {
					log.error("导入失败(第" + (r + 1) + "行,关键字未填写)");
					resBu.append("导入失败(第" + (r + 1) + "行,关键字未填写)");
				}

				// 域名
				if (row.getCell(1) != null) {
					domain = row.getCell(1).getStringCellValue();
					if (domain == null || domain.isEmpty()) {
						log.error("导入失败(第" + (r + 1) + "行,域名未填写)");
						resBu.append("导入失败(第" + (r + 1) + "行,域名未填写)");
					}
					domainStr = domain.replaceFirst("(https?://)", "");
				} else {
					log.error("导入失败(第" + (r + 1) + "行,域名未填写)");
					resBu.append("导入失败(第" + (r + 1) + "行,域名未填写)");
				}

				// 指数
				if (row.getCell(2) != null) {
					row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
					keyWordIndex = row.getCell(2).getStringCellValue();
					// if (keyWordIndex == null || keyWordIndex.isEmpty()) {
					// log.error("导入失败(第" + (r + 1) + "行,关键词指数未填写)");
					// resBu.append("导入失败(第" + (r + 1) + "行,指数未填写)");
				}
				// }else{
				// log.error("导入失败(第" + (r + 1) + "行,关键词指数未填写)");
				// resBu.append("导入失败(第" + (r + 1) + "行,指数未填写)");
				// }

				if (row.getCell(3) != null) {
					// 搜索引擎
					engine = row.getCell(3).getStringCellValue();
					if (engine == null || engine.isEmpty()) {
						log.error("导入失败(第" + (r + 1) + "行,搜索引擎未填写)");
						resBu.append("导入失败(第" + (r + 1) + "行,搜索引擎未填写)");
					}
				} else {
					log.error("导入失败(第" + (r + 1) + "行,搜索引擎未填写)");
					resBu.append("导入失败(第" + (r + 1) + "行,搜索引擎未填写)");
				}

				if (row.getCell(4) != null) {
					// 初排名
					row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
					initRanking = row.getCell(4).getStringCellValue();
					// if (initRanking == null || initRanking.isEmpty()) {
					// log.error("导入失败(第" + (r + 1) + "行,初排未填写)");
					// resBu.append("导入失败(第" + (r + 1) + "行,初排未填写)");
				}
				// }else{
				// log.error("导入失败(第" + (r + 1) + "行,初排未填写)");
				// resBu.append("导入失败(第" + (r + 1) + "行,初排未填写)");
				// }
				if (row.getCell(5) != null) {
					// 新排名
					row.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
					newRanking = row.getCell(5).getStringCellValue();
					if (newRanking == null || newRanking.isEmpty()) {
						log.error("导入失败(第" + (r + 1) + "行,新排未填写)");
						resBu.append("导入失败(第" + (r + 1) + "行,新排未填写)");
					}
				} else {
					log.error("导入失败(第" + (r + 1) + "行,新排未填写)");
					resBu.append("导入失败(第" + (r + 1) + "行,新排未填写)");
				}
				keyWord.setName(name); // 关键词
				keyWord.setDomain(domainStr); // 域名
				keyWord.setKeywordIndex(keyWordIndex); // 指数
				if (StringUtils.isNotBlank(engine)) {
					for (int i = 0; i < engineList.size(); i++) {
						Map<String, Object> engineMap = engineList.get(i);
						String engineStr = (String) engineMap.get("fuzzy");
						String code = (String) engineMap.get("code");
						boolean boo = engineStr.contains(engine);
						if (boo) {
							keyWord.setEngineCode(code);// 搜索引擎
							break;
						}

					}
				} else {
					keyWord.setEngineCode(null);// 搜索引擎
				}
				keyWord.setInitRanking(initRanking); // 初排
				if ("100+".equals(newRanking) || "-".equals(newRanking)) {
					keyWord.setNewRanking("10000");
				} else {
					keyWord.setNewRanking(newRanking);
				}

				if (!CommonUtil.isNumeric(keyWord.getNewRanking())) {
					log.error("导入失败(第" + (r + 1) + "行,最新排名不是数字)");
					resBu.append("导入失败(第" + (r + 1) + "行,最新排名不是数字)");
				}

				importNum += 1;
				keyWordSucessList.add(keyWord);
				if (resBu != null && resBu.length() > 0) {
					keyWordErrorList.add(resBu);
				}
			} catch (Exception e) {
				resBu.append("导入失败(第" + (r + 1) + "行,数据异常)");
				keyWordErrorList.add(resBu);
			}

		}
		rb.put("importNum", importNum);
		rb.put("keyWordSucessList", keyWordSucessList);
		rb.put("keyWordErrorList", keyWordErrorList);
		if (!keyWordErrorList.isEmpty()) {
			return rb.rollback();
		}

		return rb.success();
	}

	/**
	 * 查询导入
	 * 
	 * @param sheet sheet
	 * @return ReturnBody rb
	 */
	public ReturnBody engineImport(Sheet sheet) {
		ReturnBody rb = ReturnBody.init();
		List<KeyWord> keyWordSucessList = new ArrayList<KeyWord>();
		List<StringBuffer> keyWordErrorList = new ArrayList<StringBuffer>();
		List<Map<String, Object>> engineList = keywordGMapper.getEngineList();
		KeyWord keyWord;
		int importNum = 0; // 记录一共导入多少条数据

		for (int r = 1; r <= sheet.getLastRowNum(); r++) {
			StringBuffer resBu = new StringBuffer();
			if (resBu.length() > 0) {
				resBu.delete(0, resBu.length() - 1);
			}
			try {
				Row row = sheet.getRow(r);
				if (row == null) {
					continue;
				}
				keyWord = new KeyWord();
				String name = null;
				String domain = null;
				String domainStr = null;
				String engine = null;
				// String isInclude = null;
				String newRanking = null;
				// 关键词
				if (row.getCell(1) != null) {
					name = row.getCell(1).getStringCellValue();
					if (name == null || name.isEmpty()) {
						log.error("导入失败(第" + (r + 1) + "行,关键字未填写)");
						resBu.append("导入失败(第" + (r + 1) + "行,关键字未填写)");
					}
				} else {
					log.error("导入失败(第" + (r + 1) + "行,关键字未填写)");
					resBu.append("导入失败(第" + (r + 1) + "行,关键字未填写)");
				}
				if (row.getCell(2) != null) {
					// 域名
					domain = row.getCell(2).getStringCellValue();
					if (domain == null || domain.isEmpty()) {
						log.error("导入失败(第" + (r + 1) + "行,域名未填写)");
						resBu.append("导入失败(第" + (r + 1) + "行,域名未填写)");
					}
					domainStr = domain.replaceFirst("(https?://)", "");
				} else {
					log.error("导入失败(第" + (r + 1) + "行,域名未填写)");
					resBu.append("导入失败(第" + (r + 1) + "行,域名未填写)");
				}
				if (row.getCell(3) != null) {
					// 搜索引擎
					engine = row.getCell(3).getStringCellValue();
					if (engine == null || engine.isEmpty()) {
						log.error("导入失败(第" + (r + 1) + "行,搜索引擎未填写)");
						resBu.append("导入失败(第" + (r + 1) + "行,搜索引擎未填写)");
					}
				} else {
					log.error("导入失败(第" + (r + 1) + "行,搜索引擎未填写)");
					resBu.append("导入失败(第" + (r + 1) + "行,搜索引擎未填写)");
				}
				// if(row.getCell(4)!=null){
				// // 收录
				// row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
				// isInclude = row.getCell(4).getStringCellValue();
				// if (isInclude == null || isInclude.isEmpty()) {
				// log.error("导入失败(第" + (r + 1) + "行,收录未填写)");
				// resBu.append("导入失败(第" + (r + 1) + "行,收录未填写)");
				// }
				// }else{
				// log.error("导入失败(第" + (r + 1) + "行,收录未填写)");
				// resBu.append("导入失败(第" + (r + 1) + "行,收录未填写)");
				// }
				if (row.getCell(5) != null) {
					// 排名
					row.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
					newRanking = row.getCell(5).getStringCellValue();
					if (newRanking == null || newRanking.isEmpty()) {
						log.error("导入失败(第" + (r + 1) + "行,新排未填写)");
						resBu.append("导入失败(第" + (r + 1) + "行,新排未填写)");
					}
				} else {
					log.error("导入失败(第" + (r + 1) + "行,新排未填写)");
					resBu.append("导入失败(第" + (r + 1) + "行,新排未填写)");
				}
				keyWord.setName(name); // 关键词
				keyWord.setDomain(domainStr); // 域名
				if (StringUtils.isNotBlank(engine)) {
					for (int i = 0; i < engineList.size(); i++) {
						Map<String, Object> engineMap = engineList.get(i);
						String engineStr = (String) engineMap.get("fuzzy");
						String code = (String) engineMap.get("code");
						boolean boo = engineStr.contains(engine);
						if (boo) {
							keyWord.setEngineCode(code);// 搜索引擎
							break;
						}

					}
				} else {
					keyWord.setEngineCode(null);// 搜索引擎
				}

				if ("100+".equals(newRanking) || "-".equals(newRanking)) {
					keyWord.setNewRanking("10000");
				} else {
					keyWord.setNewRanking(newRanking);
				}
				if (!CommonUtil.isNumeric(keyWord.getNewRanking())) {
					log.error("导入失败(第" + (r + 1) + "行,最新排名不是数字)");
					resBu.append("导入失败(第" + (r + 1) + "行,最新排名不是数字)");
				}

				importNum += 1;
				keyWordSucessList.add(keyWord);
				if (resBu != null && resBu.length() > 0) {
					keyWordErrorList.add(resBu);
				}
			} catch (Exception e) {
				resBu.append("导入失败(第" + (r + 1) + "行,异常)");
				keyWordErrorList.add(resBu);
			}
		}
		rb.put("importNum", importNum);
		rb.put("keyWordSucessList", keyWordSucessList);
		rb.put("keyWordErrorList", keyWordErrorList);
		if (!keyWordErrorList.isEmpty()) {
			return rb.rollback();
		}
		return rb.success();
	}

	/**
	 * 导出
	 */
	public XSSFWorkbook exportKeyWord(@RequestParam Map<String, Object> pam, HttpServletResponse response)
			throws Exception {
		XSSFWorkbook workbook = new XSSFWorkbook();
		try {
			XSSFSheet sheet = workbook.createSheet("信息表");
			List<Map<String, Object>> engineList = keywordGMapper.getEngineList(); // 搜索引擎配置
			List<Map<String, Object>> keyWordExportList = keywordGMapper.getExprotKeyWordList(pam); // 导出数据
			String fileName = "关键词列表-" + DateUtil.getDay() + ".xlsx";// 设置要导出的文件的名字
			// 新增数据行，并且设置单元格数据

			int rowNum = 1;
			String[] headers = { "关键词", "域名", "搜索引擎", "当前排名", "使用状态" };
			// headers表示excel表中第一行的表头

			XSSFRow row = sheet.createRow(0);
			// 在excel表中添加表头

			for (int i = 0; i < headers.length; i++) {
				XSSFCell cell = row.createCell(i);
				XSSFRichTextString text = new XSSFRichTextString(headers[i]);
				cell.setCellValue(text);
			}
			Map<String, Object> keyWordExportMap = null;
			// 在表中存放查询到的数据放入对应的列
			for (int i = 0; i < keyWordExportList.size(); i++) {
				XSSFRow row1 = sheet.createRow(rowNum);
				keyWordExportMap = keyWordExportList.get(i);
				String domainType = (String) keyWordExportMap.get("domain_type");
				String domain = domainType + (String) keyWordExportMap.get("domain");
				String engineCode = (String) keyWordExportMap.get("engineCode");
				String engineStr = null;
				for (int j = 0; j < engineList.size(); j++) {
					Map<String, Object> engineMap = engineList.get(j);
					String code = (String) engineMap.get("code");
					if (code.equals(engineCode)) {
						engineStr = (String) engineMap.get("name");// 搜索引擎
						break;
					}
				}
				String state = (String) keyWordExportMap.get("state");
				String stateStr = null;
				if ("02".equals(state)) {
					stateStr = "已停用";
				} else if ("00".equals(state)) {
					stateStr = "待审核";
				} else {
					stateStr = "使用中";
				}
				row1.createCell(0).setCellValue(keyWordExportMap.get("keyWordName").toString());
				row1.createCell(1).setCellValue(domain);
				row1.createCell(2).setCellValue(engineStr);
				row1.createCell(3).setCellValue(keyWordExportMap.get("newRanking").toString());
				row1.createCell(4).setCellValue(stateStr);
				rowNum++;
			}
			response.setContentType("application/octet-stream");
			response.setHeader("Content-disposition",
					"attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
			response.flushBuffer();
			workbook.write(response.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return workbook;
	}

	/**
	 * 修改价格和类型
	 */
	public ReturnBody updatePriceAndTargetRanking(Map<String, Object> pam) {
		ReturnBody rb = ReturnBody.init();
		try {
			int num = keywordGMapper.updatePriceAndTargetRanking(pam);
			if (num == 0) {
				return rb.rollback();
			}
			num = keywordGMapper.updateChildPrice(pam);
			if (num == 0) {
				return rb.rollback();
			}
			return rb.success();
		} catch (Exception e) {
			log.error("异常-{}", e);
			return rb.rollback();
		} finally {
			rb.result();
		}
	}

	/**
	 * 添加厂商
	 */
	public ReturnBody addVender(Map<String, Object> pam) {
		ReturnBody rb = ReturnBody.init();
		try {
			int num = keywordGMapper.addVender(pam);
			if (num == 0) {
				return rb.rollback();
			}
			return rb.success();
		} catch (Exception e) {
			log.error("异常-{}", e);
			return rb.rollback();
		} finally {
			rb.result();
		}
	}

	/**
	 * 删除厂商
	 */
	public ReturnBody deleteVender(Map<String, Object> pam) {
		ReturnBody rb = ReturnBody.init();
		try {
			int num = keywordGMapper.deleteVender(pam);
			if (num == 0) {
				return rb.rollback();
			}
			return rb.success();
		} catch (Exception e) {
			log.error("异常-{}", e);
			return rb.rollback();
		} finally {
			rb.result();
		}
	}

	/**
	 * 获取手机引擎
	 * 
	 * @return
	 */
	public List<Map<String, Object>> getEngineList() {
		return keywordGMapper.getEngineList();
	}

	/**
	 * 修改最新排名
	 */
	public ReturnBody updateNewRanking(Map<String, Object> pam) {

		String importime = DateUtil.yMdToYmdmds(DateUtil.getDay());

		return updateNewRanking(pam, importime);

	}

	/**
	 * 修改最新排名
	 */
	public ReturnBody updateNewRanking(Map<String, Object> pam, String importime) {
		ReturnBody rb = ReturnBody.init();
		try {
			List<KeyWord> keyWordSucessList = new ArrayList<KeyWord>();
			List<StringBuffer> keyWordErrorList = new ArrayList<StringBuffer>();
			KeyWord keyWord = new KeyWord();
			StringBuffer resBu = new StringBuffer();
			if (pam != null) {
				String name = (String) pam.get("name");
				String domain = (String) pam.get("domain");
				String engine_code = (String) pam.get("engine_code");
				String newRanking = (String) pam.get("newRanking");
				if (StringUtils.isNotEmpty(name)) {
					keyWord.setName(name); // 关键词
				} else {
					resBu.append("传入关键字为空");
				}
				if (StringUtils.isNotEmpty(domain)) {
					keyWord.setDomain(domain); // 域名
				} else {
					resBu.append("传入域名为空");
				}
				if (StringUtils.isNotEmpty(engine_code)) {
					keyWord.setEngineCode(engine_code);// 搜索引擎
				} else {
					resBu.append("传入搜索引擎为空");
				}
				if (StringUtils.isNotEmpty(newRanking)) {
					keyWord.setNewRanking(newRanking.toString()); // 新排
				} else {
					resBu.append("传入最新排名为空");
				}
			} else {
				resBu.append("传入的map对象为空");
			}
			keyWordSucessList.add(keyWord);
			if (resBu != null && resBu.length() > 0) {
				keyWordErrorList.add(resBu);
			}
			rb.put("keyWordSucessList", keyWordSucessList);
			rb.put("keyWordErrorList", keyWordErrorList);
			if (!keyWordErrorList.isEmpty()) {
				return rb.rollback();
			}
			rb = importDataToDataBase(rb, importime);
			return rb;
		} catch (Exception e) {
			log.error("异常-{}", e);
			return rb.rollback();
		} finally {
			rb.result();
		}

	}

	/**
	 * 修改昨日排名 只是把importime时间调成昨天即可
	 */
	public ReturnBody updateYesRanking(Map<String, Object> pam) {
		String runTime = (String) pam.get("run_time");
		String importime = DateUtil.yMdToYmdmds(DateUtil.getAfterDayDate(runTime, -1, -1));

		return updateNewRanking(pam, importime);

	}

	/**
	 * 关键词审核
	 */
	public void updatekeyWordReviewDisabled(Map<String, Object> pam) {
		try {
			keywordGMapper.updatekeyWordReviewDisabled(pam);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	@Override
	public List<Map<String, Object>> getApiKeyWordsList(Map<String, Object> params) {
		return keywordGMapper.getApiKeyWordsList(params);
	}
	
	public List<Map<String, Object>> getApiErrorList() {
		return apiErrorList;
	}

	public void handelNewRankingByApi(Map<String, Object> params) {
		apiErrorList.clear();
		String apiType = (String)params.getOrDefault("apiType", "02");
		boolean isAll = (boolean) params.get("isAll");
		KeywordGService ks = (KeywordGServiceImpl) AopContext.currentProxy();
		long id = 0;
		int num = 0;
		params.put("id", id);
		params.put("num", 1000);
		while (true) {
			List<Map<String, Object>> keyWordsList = ks.getApiKeyWordsList(params);

			if (keyWordsList != null && keyWordsList.size() > 0) {
				for (Map<String, Object> keyWord : keyWordsList) {
					id = (long) keyWord.get("id");
					String importime = DateUtil.yMdToYmdmds(DateUtil.getDay());
					String runTime = (String) keyWord.get("run_time");
					if (isAll || (!isAll && (StringUtils.isEmpty(runTime) || importime.compareTo(runTime) > 0))) {
						if("01".equals(apiType)) {
							threadPoolExecutor.execute(new KeywrodsTask(keyWord, CustomUtil.random(10, 300), ++num));
						}else if("02".equals(apiType)){
							threadPoolExecutor.execute(new KeywrodsZzgjTask(keyWord, CustomUtil.random(10, 300), ++num));
						}
					}
				}

			}

			if (keyWordsList.size() == 1000) {
				params.put("id", id);
			} else {
				break;
			}
		}
	}

	class KeywrodsTask implements Runnable {

		private Map<String, Object> keyWord;

		private int sleepTime;

		private int num;

		public KeywrodsTask(Map<String, Object> keyWord, int sleepTime, int num) {
			this.keyWord = keyWord;
			this.sleepTime = sleepTime;
			this.num = num;
		}

		@Override
		public void run() {

			try {
				Thread.sleep(sleepTime);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			String importime = DateUtil.yMdToYmdmds(DateUtil.getDay());
			log.info("获取任务taskid开始:[{}],日期:[{}]", keyWord, importime);
			String engine_code = (String) keyWord.get("engine_code");
			String url = "01".equals(engine_code) ? baidupcUrl : baidumobileUrl;
			String keywords = (String) keyWord.get("name");
			String domain = (String) keyWord.get("domain");

			String apikey = "01".equals(engine_code) ? baidupcApikey : baidumobileApikey;
			Map<String, String> headers = new HashMap<>();

			headers.put("Content-type", "application/x-www-form-urlencoded");
			headers.put("Authorization", "APIKEY " + apikey);

			Map<String, String> params = new HashMap<>();
			params.put("url", domain);
			params.put("keywords", keywords);

			String res = HttpClientManagerT.postData(url, params, headers);
			log.info("response:{}", res);
			JSONObject resultJson = JSON.parseObject(res);
			String errcode = resultJson.getString("errcode");
			String errmsg = resultJson.getString("errmsg");
			if (!"0".equals(errcode) && StringUtils.isNotEmpty(errmsg)) {
				log.error("-------获取任务id异常--------");
				if ("100102".equals(errcode) || "100103".equals(errcode) || "100104".equals(errcode)) {
					threadPoolExecutor.execute(new KeywrodsTask(keyWord, CustomUtil.random(500, 3000), num));
				}

			} else {
				String taskid = resultJson.getJSONObject("data").getString("taskid");
				log.info("获取任务id[{}]成功，放入延迟队列，num[{}]", taskid, num);
				scheduledExecutor.schedule(new ScheduledRunTask(taskid, url, importime, headers, params, keyWord), 60,
						TimeUnit.SECONDS);
			}
		}

	}

	class ScheduledRunTask implements Runnable {

		private String taskid;
		private String url;
		private String importime;
		private Map<String, String> headers;
		private Map<String, String> params;
		private Map<String, Object> keyWord;

		public ScheduledRunTask(String taskid, String url, String importime, Map<String, String> headers,
				Map<String, String> params, Map<String, Object> keyWord) {
			this.taskid = taskid;
			this.importime = importime;
			this.headers = headers;
			this.url = url;
			this.params = params;
			this.keyWord = keyWord;
		}

		@Override
		public void run() {
			log.info("获取排名开始:[{}],任务id:[{}]", params, taskid);
			Map<String, String> rparams = new HashMap<>();
			rparams.put("taskid", taskid);

			String res = HttpClientManagerT.postData(url, rparams, headers);
			log.info("response:{}", res);
			JSONObject resultJson = JSON.parseObject(res);
			String errcode = resultJson.getString("errcode");
			String errmsg = resultJson.getString("errmsg");
			if (!"0".equals(errcode) && StringUtils.isNotEmpty(errmsg)) {
				log.error("-------获取排名异常--------");
				if ("200104".equals(errcode) || "100102".equals(errcode) || "100103".equals(errcode)
						|| "100104".equals(errcode)) {
					log.info("[{}]数据采集中，重新放回队列", taskid);
					scheduledExecutor.schedule(new ScheduledRunTask(taskid, url, importime, headers, params, keyWord),
							60, TimeUnit.SECONDS);
				}

			} else {
				log.info("更新排名");
				int rank = 10000;
				com.alibaba.fastjson.JSONArray keywordmonitor = resultJson.getJSONObject("data")
						.getJSONArray("keywordmonitor");
				if (keywordmonitor != null && keywordmonitor.size() > 0) {
					com.alibaba.fastjson.JSONArray ranks = keywordmonitor.getJSONObject(0).getJSONArray("ranks");
					if (ranks != null && ranks.size() > 0) {
						int r = ranks.getJSONObject(0).getIntValue("rank");
						if (r < 100) {
							rank = r;
						}
					}
				}

				keyWord.put("newRanking", String.valueOf(rank));
				log.info("参数：[{}],importime:[{}]", keyWord, importime);
				KeywordGService ks = context.getBean(KeywordGServiceImpl.class);
				ReturnBody rb = ReturnBody.init();
				rb.run(ks.updateNewRanking(keyWord, importime));
				log.info("更新结果:[{}]",rb.getResult());
			}

		}

	}

	class KeywrodsZzgjTask implements Runnable {

		private Map<String, Object> keyWord;

		private int sleepTime;

		private int num;

		public KeywrodsZzgjTask(Map<String, Object> keyWord, int sleepTime, int num) {
			this.keyWord = keyWord;
			this.sleepTime = sleepTime;
			this.num = num;
		}

		@Override
		public void run() {

			try {
				Thread.sleep(sleepTime);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			String importime = DateUtil.yMdToYmdmds(DateUtil.getDay());
			log.info("站长工具，获取排名开始:[{}],日期:[{}],num[{}]", keyWord, importime, num);
			String engine_code = (String) keyWord.get("engine_code");
			String url = "01".equals(engine_code) ? keywrodsConfig.getZzgjBaidupcUrl() : keywrodsConfig.getZzgjBaidumobileUrl();
			String keywords = (String) keyWord.get("name");
			String domain = (String) keyWord.get("domain");

			Map<String, String> params = new HashMap<>();
			params.put("domainName", domain);
			params.put("keyword", keywords);
			params.put("key", keywrodsConfig.getZzgjKey());
			params.put("top100", "false");

			String res = HttpClientManagerT.postData(url, params, null);
			log.info("response:{}", res);
			
			int rank = getRank(res);
			
			keyWord.put("newRanking", String.valueOf(rank));
			log.info("参数：[{}],importime:[{}]", keyWord, importime);
			KeywordGService ks = context.getBean(KeywordGServiceImpl.class);
			ReturnBody rb = ReturnBody.init();
			rb.run(ks.updateNewRanking(keyWord, importime));
			log.info("更新结果:[{}]",rb.getResult());
		}
		
		private int getRank(String res) {
			int rank = 10000;
			if (StringUtils.isEmpty(res)) {
				log.error("-------站长工具，获取排名异常--------");
				log.error("排名返回结果为空");
				return rank;
			}
			JSONObject resultJson = JSON.parseObject(res);
			
			if (resultJson == null) {
				log.error("-------站长工具，获取排名异常--------");
				log.error("排名返回结果为空");
				return rank;
			}
			
			int stateCode = resultJson.getInteger("StateCode");
			String reason = resultJson.getString("Reason");
			if (stateCode == 1) {
				JSONObject result = (JSONObject) resultJson.get("Result");
				com.alibaba.fastjson.JSONArray ranks = result.getJSONArray("Ranks");
				if (ranks != null && ranks.size() > 0) {
					JSONObject rankObj = ranks.getJSONObject(0);
					String rankStr = rankObj.getString("RankStr");
					String[] ranking = rankStr.split("-");
					Integer rank1 = Integer.parseInt(ranking[0]);
					Integer rank2 = Integer.parseInt(ranking[1]);
					rank = (rank1 - 1) * 10 + rank2;
				} 
			} else {
				log.error("-------站长工具，获取排名异常--------");
				log.error("排名返回结果[{}][{}]", stateCode, reason);
			}
			return rank;
		}

	}
	
	public void testTask() {
		Map<String, Object> keyWord = new HashMap<>();
		keyWord.put("domain", "www.tushuz.com");
		keyWord.put("name", "食品经营许可证需要什么材料");
		keyWord.put("engine_code", "01");
		keyWord.put("id", 12497);
		keyWord.put("apiType", "02");

		threadPoolExecutor.execute(new KeywrodsTask(keyWord, 50, 0));
	}

	public String getBaidupcUrl() {
		return baidupcUrl;
	}

	public void setBaidupcUrl(String baidupcUrl) {
		this.baidupcUrl = baidupcUrl;
	}

	public String getBaidumobileUrl() {
		return baidumobileUrl;
	}

	public void setBaidumobileUrl(String baidumobileUrl) {
		this.baidumobileUrl = baidumobileUrl;
	}

	public String getBaidupcApikey() {
		return baidupcApikey;
	}

	public void setBaidupcApikey(String baidupcApikey) {
		this.baidupcApikey = baidupcApikey;
	}

	public String getBaidumobileApikey() {
		return baidumobileApikey;
	}

	public void setBaidumobileApikey(String baidumobileApikey) {
		this.baidumobileApikey = baidumobileApikey;
	}

	public static void main(String[] args) {
		KeywordGServiceImpl aa = new KeywordGServiceImpl();
		aa.setBaidupcUrl("http://apis.5118.com/morerank/baidupc");
		aa.setBaidupcApikey("64C1561B2E664FE7B7DB1F25F490BCE7");
		aa.setBaidumobileUrl("http://apis.5118.com/morerank/baidumobile");
		aa.setBaidumobileApikey("55027CE4B36446318866F91E1D15A72C");

		aa.testTask();

		try {
			Thread.sleep(100000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
